package com.sword.invoice.channel.lq.utils;

import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
import java.util.Random;

/**
 * @Author zhangshiheng
 * @Date 2023-01-31 17:44
 * @Version 1.0
 **/
public class SM4Util {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final Charset ENCODING = StandardCharsets.UTF_8;
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 生成ECB暗号
     *
     * @param algorithmName 算法名称
     * @param mode          模式
     * @param key           密码
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

/**
 * sm4加密
 *
 * @param hexKey   16进制密钥（忽略大小写）
 * @param paramStr 待加密字符串
 * @return 返回Base64后加密字符串
     * @explain 加密模式：ECB
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // String-->byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 加密后的数组
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        // byte[]-->hexString
        String cipherText = Base64.getEncoder().encodeToString(cipherArray);
        return cipherText;
    }
/**
 * sm4加密
 *
 * @param hexKey   16进制密钥（忽略大小写）
 * @param paramStr 待加密字符串
 * @return 返回Base64后加密字符串
     * @explain 加密模式：ECB
     */
    public static byte[] encryptEcb(String hexKey, byte[] paramStr) throws Exception {
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 加密后的数组
        return encrypt_Ecb_Padding(keyData, paramStr);
    }

    /**
     * 加密模式为ECB
     *
     * @param key  2进制密钥
     * @param data 2进制原文
     * @return 二进制密文
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }
    /**
     * sm4解密
     *
     * @param hexKey     16进制密钥
     * @param cipherText 16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @explain 解密模式：采用ECB
     */
    @SuppressWarnings("UnnecessaryLocalVariable")
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // hexString-->byte[]
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        // 解密
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        // 接收解密后的字符串 byte[]-->String
        String decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }
    /**
     * sm4解密
     *
     * @param hexKey     16进制密钥
     * @param cipherText 16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @explain 解密模式：采用ECB
     */
    @SuppressWarnings("UnnecessaryLocalVariable")
    public static byte[] decryptEcb(String hexKey, byte[] cipherText) throws Exception {
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 解密
        return decrypt_Ecb_Padding(keyData, cipherText);
    }

    /**
     * sm4解密
     *
     * @param key  2进制密钥
     * @param cipherText 2进制密文
     * @return 解密后的2进制原文
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    public static void main(String[] args) {

        String SM4_KEY=generateKey16Str();
        System.out.println("密钥======="+SM4_KEY);
        System.out.println("授权码：" + authCode());
//        String SM4_KEY="8ad828f3cbc6350f187ca0f2a2e76ac8";
        JSONObject json=new JSONObject();
        json.put("nsrsbh","9151010020260067X4");
        String content=json.toJSONString();

        String encryptHex = null;
        String decryptStr =null;
        try {
            encryptHex = SM4Util.encryptEcb(SM4_KEY,content);
            decryptStr = SM4Util.decryptEcb(SM4_KEY,encryptHex);
//            JSONObject response=JSONObject.parseObject("{\n" +
//                    "\t\"httpStatusCode\": 200,\n" +
//                    "\t\"body\": \"{\\\"Response\\\":{\\\"RequestId\\\":\\\"5fb8ea6f204ab401\\\",\\\"Data\\\":\\\"bKsZ20sDdwmCsqPwgk1DvUQbsI7lGkT+nbE2bGnBdCBk/wV4x89FQnBoDPQHIz/J6uun5ZKOivoeXGylVQCtTbHBG87ObS7rQa5OHRM/z7nnvy9ZrZRstvrAyr9QbF1E/aJHEVqm91nZryaka1VUpQY3dlYwNN0TgImyUkrmdwbvlfyW9cKLcDlwSEv7aQbnRm8w5B+0oNHzX6BD0F4T/1QtG5cUkY4DRJ/auxrjtnC/Uix57kQ1dSy/j4wx93e4ndJzilH6gpGCl9Y1xbLFdxoEulg0NRuS1GHv7BlxiscCJWqvNragy2oMHdlegRHr97golbWJDiYffmo1Pmh0HIrjakEmeYfaupyVxngdXO2zP0ZqKdtCxQAfVeAVrI9FjHWaAVVZx8lGCuh9rTrnhKz08s5aFe9UJv7WYPKa0VOyVtc27SjbCp2yraHIl0tzp0B+p7Gt/ofHVboNlkZWqj/H25vLbZxYDKmblyX77yOwySR1GtkxBlUIbhVh2RjILmdnpQ0Ts5P+58xuI3A8Qn01kjDHaSxujqDofQ4hvZcSPYIIMKFp9JnznzA0Gy+j9z/TgupAXSO+Kt8PHFpHOEdmxfQFGbiBEPkVDdZz0Ad0oNK947dm93OTD1Pwly8RU5usVbh4xPljV2be1ZBrYF0a9BEFxvaka/7rQqytsR5VByKIj9Eqgr8rJlgDKavCmW3g9hYb0MNWes8uqZDvAzTkJAIT0C41jbDOlos7lG4N/0FOcliWZtmXZ0qPXqKsj1KuB4Wvht4WZ+DuHhEPnTVqBkFIljBOa4+B1064QrFnmJdeiSZXG048SXvJy0bCpVHLiq8SbqGuKrg0yQ0B0DcvU+4sdQs+E9waQv6VTk+Ito1+hUpg1K5tlDEXBQC9PrLwjuSa+QiEUvgg5XniwoLKMeEYRcjumyD7lPcJUbFCR37e29wS4trZR1k46bHqI2UW69NYFXyns3tGvdZzZbrQdOROZYaHKTZ+OkMfpI3Xy+UwYIPrvatSRr86ZKnwaU3qzr041PjzISVBxmJnN1METZk5SFR4xtInmM7G1vXhWDz3JPnT732Rs2Ervdj70fI0L/EO0evAgWbWtH/NSRWLBFDy0apKe/IUiPEnUAY=\\\"}}\"\n" +
//                    "}");
//
//             decryptStr = SM4Util.decryptEcb(SM4_KEY,response
//                    .getJSONObject("body")
//                    .getJSONObject("Response")
//                    .getString("Data")
//            );

        } catch (Exception e) {
            e.printStackTrace();
        }


//        System.out.println("明文======="+decryptStr);
        System.out.println("加密前======="+content);
        System.out.println("解密后======="+decryptStr);


    }

    /**
     * 随机生成32位16进制密钥字符串
     * @return
     */
    public static String generateKey16Str(){
        StringBuilder hexStringBuffer = new StringBuilder();
        try {
            byte[] keyBytes=generateKey();
            for (byte b : keyBytes) {
                String hexString = String.format("%02X", b);
                // 将转换后的十六进制字符串添加到字符串缓冲区中
                hexStringBuffer.append(hexString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       return hexStringBuffer.toString();
    }
    /**
     * 自动生成密钥
     * @explain
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    /**
     * 授权码
     */
    public static String authCode() {
        String characters = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            int index = random.nextInt(characters.length());
            code.append(characters.charAt(index));
        }
        return code.toString();
    }

    /**
     * @explain
     * @param keySize
     * @return
     * @throws Exception
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

}

